package com.entitymapper.driver.impl;

import java.io.IOException;

import org.apache.log4j.Logger;

import com.entitymapper.EntityMapperException;
import com.entitymapper.EntityStatusException;
import com.entitymapper.driver.Driver;
import com.entitymapper.driver.Format;
import com.entitymapper.field.ResultSet;
import com.entitymapper.field.impl.RFIDResultSet;
import com.rfid.RFIDCallException;
import com.rfid.RFIDCaller;
import com.rfid.jni.JNI_RFIDCaller;
import com.rfid.jni.RFIDStatusException;

public class RFIDDriver implements Driver {

	private RFIDCaller caller;
	
	private static final Logger log = Logger.getLogger(RFIDDriver.class);
	
	private Class<? extends ResultSet> resultSetClass;
	
	public RFIDDriver() {
		this.resultSetClass = RFIDResultSet.class;
		try {
			this.caller = new JNI_RFIDCaller();
		} catch (IOException e) {
			log.error(e);
			throw new EntityMapperException("create caller:" + JNI_RFIDCaller.class + " fail for reason:", e);
		}
	}
	
	@Override
	public String read(Format format)throws EntityMapperException{
		RFIDFormat fm = (RFIDFormat) format;
		try {
			return caller.read(fm.getAreaCount(), fm.getAreaStart());
		}catch(IOException e) {
			log.error("reading error, because :"+e.getMessage());
			if(e instanceof RFIDStatusException) {
				RFIDStatusException se = (RFIDStatusException)e;
				throw new EntityStatusException(se.getStatus());
			}else {
				throw new EntityMapperException(e);
			}
		}
	}

	@Override
	public void write(Format format, String data) throws EntityMapperException {
		RFIDFormat fm = (RFIDFormat) format;
		try {
			caller.write(fm.getAreaCount(), fm.getAreaStart(), data);
		} catch (RFIDCallException e) {
			log.error("writing error, because :"+e.getMessage());
			if(e instanceof RFIDStatusException) {
				RFIDStatusException se = (RFIDStatusException)e;
				throw new EntityStatusException(se.getStatus());
			}else {
				throw new EntityMapperException(e);
			}
		}
	}

	public RFIDCaller getCaller() {
		return caller;
	}
	public void setCaller(RFIDCaller caller) {
		this.caller = caller;
	}

	public Class<? extends ResultSet> getResultSetClass() {
		return resultSetClass;
	}

	

	
	
}
